package com.jiyongjun.bms.tool;

import com.jiyongjun.bms.tool.exception.BizException;
import com.jiyongjun.bms.tool.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * description: 克隆工具类
 *
 * @author yongjun.ji
 * @date 2018/6/26 18:29
 */
public class CloneUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloneUtil.class);

    /**
     * 深克隆,被克隆对象必须实现Cloneable接口
     * @param originObj
     * @param <T>
     * @return
     */
    public static <T> T deepClone(T originObj) {
        if (originObj == null) {
            throw new BizException("originObj can not be null!");
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
            try (ObjectOutputStream oos = new ObjectOutputStream(baos)){
                oos.writeObject(originObj);
                try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())){
                    try (ObjectInputStream ois = new ObjectInputStream(bais)){
                        return (T) ois.readObject();
                    }
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        } 
    }
}
